<template>

  <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="150px">
    <el-card>

      <el-row :gutter="20">

        <el-col :span="12">
          <el-form-item label="试题类型 " prop="quType">
            <dic-list-select v-model="postForm.quType" :disabled="update" :excludes="excludeTypes" dic-code="qu_type" title="请选择题型" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="12">
          <el-form-item label="所属题库" prop="repoId">
            <repo-select v-model="postForm.repoId" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="12">
          <el-form-item label="难度等级 " prop="level">
            <dic-list-select v-model="postForm.level" dic-code="qu_level" title="请选择难度等级" />
          </el-form-item>
        </el-col>
        <el-col v-if="!child" :span="12">
          <el-form-item label="所属章节">
            <chapter-select v-model="postForm.chapterId" :repo-id="postForm.repoId" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="试题内容" prop="content">
            <Tinymce ref="content" v-model="postForm.content" :height="200" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="整题解析" prop="oriPrice">
            <Tinymce ref="analysis" v-model="postForm.analysis" :height="200" />
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if="postForm.quType && postForm.quType!=='4' && postForm.quType!=='6' && postForm.quType!=='99'" class="filter-container" style="margin-top: 25px">

        <el-button :disabled="postForm.answerList.length >= 8 || (postForm.quType==='3' && postForm.answerList.length>=2)" class="filter-item" type="primary" icon="el-icon-plus" size="small" plain @click="handleAdd">
          添加选项
        </el-button>

        <el-table
          :data="postForm.answerList"
          :border="true"
          row-key="id"
          style="width: 100%;"
        >
          <el-table-column
            v-if="itemIsAnswer"
            label="是否答案"
            width="100"
            align="center"
          >
            <template v-slot="scope">
              <el-checkbox v-model="scope.row.isRight" @change="answerChange(scope.$index)">答案</el-checkbox>
            </template>

          </el-table-column>

          <el-table-column
            v-if="itemImage"
            label="选项图片"
            width="120px"
            align="center"
          >
            <template v-slot="scope">

              <file-upload
                v-model="scope.row.image"
              />

            </template>
          </el-table-column>

          <el-table-column
            label="选项内容"
          >
            <template v-slot="scope">
              <el-input v-model="scope.row.content" :placeholder="postForm.quType==='5'?'填空题支持多个近似答案用||隔开，如：10||十，学员填写`10`或者`十`都判为正确':'输入选项内容'" size="small" type="textarea" />
            </template>
          </el-table-column>

          <el-table-column
            v-if="itemAnalysis"
            label="选项解析"
          >
            <template v-slot="scope">
              <el-input v-model="scope.row.analysis" size="small" type="textarea" />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              <el-button type="danger" icon="el-icon-delete" circle @click="removeItem(scope.$index, $event)" />
            </template>
          </el-table-column>

        </el-table>

        <div v-if="postForm.quType==='5'" style="margin-top: 10px">
          <el-checkbox v-model="postForm.answerOrder" label="严格按序作答"/>
        </div>

      </div>

    </el-card>

  </el-form>
</template>

<script>
import ChapterSelect from '@/components/ChapterSelect'
import DicListSelect from '@/components/DicListSelect'
import FileUpload from '@/components/FileUpload'
import Tinymce from '@/components/Tinymce'
import RepoSelect from '@/components/RepoSelect'

export default {
  name: 'QuItemSave',
  components: { RepoSelect, Tinymce, FileUpload, DicListSelect, ChapterSelect },
  props: {
    value: Object,
    child: {
      type: Boolean,
      default: false
    },
    update: Boolean,
    excludeTypes: Array
  },
  data() {
    return {

      initContent: false,
      initAnalysis: false,

      // 不同题型的显示项目
      itemImage: true,
      itemAnalysis: true,
      itemIsAnswer: true,

      // 初始化表单数据
      postForm: {
        quType: '',
        repoId: '',
        answerList: []
      },
      rules: {
        content: [
          { required: true, message: '试题内容不能为空！' }
        ],

        quType: [
          { required: true, message: '试题类型不能为空！' }
        ],

        level: [
          { required: true, message: '必须选择难度等级！' }
        ],

        repoId: [
          { required: true, message: '请选择题库！' }
        ]
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        this.postForm = val
        this.initValue(false)
      },
      deep: true
    },

    // 变换题型
    'postForm.quType': {
      handler(val) {
        // 添加模式允许改题型
        if (!this.update) {
          this.handleTypeChange(val)
        }
      }
    },
    postForm: {
      handler(val) {
        this.$emit('input', val)
        this.$emit('change', val)
      },
      deep: true
    }
  },

  created() {
    this.postForm = this.value
    // 初始化
    this.$nextTick(() => {
      setTimeout(() => {
        this.initValue(true)
      }, 1000)
    })
  },
  methods: {

    // 添加时选择题型做对应的智能填充
    handleTypeChange(v) {
      // 填空题和组合题
      if (v === '5' || v === '99') {
        this.itemImage = false
        this.itemAnalysis = false
        this.itemIsAnswer = false
      } else {
        this.itemImage = true
        this.itemAnalysis = true
        this.itemIsAnswer = true
      }

      // 清空并填充
      this.postForm.answerList = []
      if (v === '3') {
        this.postForm.answerList.push({ isRight: true, content: '正确', analysis: '' })
        this.postForm.answerList.push({ isRight: false, content: '错误', analysis: '' })
      }

      // 单选多选默认增加3个
      if (v === '1' || v === '2') {
        for (let i = 0; i < 3; i++) {
          this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
        }
      }

      if (v === '5') {
        for (let i = 0; i < 2; i++) {
          this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
        }
      }
    },

    // 添加子项
    handleAdd() {
      this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
    },

    // 添加连线分组
    handleAddGroup() {
      this.postForm.answerGroup.push([{ isRight: true, content: '' }, { isRight: true, content: '' }])
    },

    removeItem(index) {
      this.postForm.answerList.splice(index, 1)
    },

    initValue(init) {
      // 填空题不需要那些东西
      if (this.postForm.quType === '5') {
        this.itemImage = false
        this.itemAnalysis = false
        this.itemIsAnswer = false
      } else {
        this.itemImage = true
        this.itemAnalysis = true
        this.itemIsAnswer = true
      }

      // 首次初始化
      if (init) {
        // 填充内容
        if (this.$refs.content) {
          this.$refs.content.setContent(this.postForm.content)
        }

        if (this.$refs.analysis) {
          this.$refs.analysis.setContent(this.postForm.analysis)
        }
      }
    },

    // 单选题互斥不选定多个
    answerChange(index, e) {
      // 类型
      if (this.postForm && (this.postForm.quType === '1' || this.postForm.quType === '3')) {
        for (let i = 0; i < this.postForm.answerList.length; i++) {
          if (index !== i) {
            this.postForm.answerList[i].isRight = false
          }
        }
      }
    },

    // 同步获得验证结果
    async validate() {
      const valid = await this.$refs.postForm.validate().catch((err) => { return err })
      return valid
    },

    // 清理内容
    clear() {
      const quType = this.postForm.quType
      const repoId = this.postForm.repoId
      const level = this.postForm.level
      const chapterId = this.postForm.chapterId

      this.postForm = {
        quType: quType,
        repoId: repoId,
        level: level,
        chapterId: chapterId,
        answerList: [],
        subList: []
      }

      // 重新选择一下
      this.handleTypeChange(quType)

      // 填充内容
      if (this.$refs.content) {
        this.$refs.content.setContent('')
      }

      if (this.$refs.analysis) {
        this.$refs.analysis.setContent('')
      }
    }

  }
}
</script>

